package com.zandequan.modules.oss.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.google.gson.Gson;
import com.zandequan.common.exception.RRException;
import com.zandequan.common.utils.*;
import com.zandequan.common.validator.group.QcloudGroup;
import com.zandequan.common.validator.group.QiniuGroup;
import com.zandequan.modules.oss.entity.SysOssEntity;
import com.zandequan.modules.sys.controller.AbstractController;
import com.zandequan.modules.sys.service.SysConfigService;
import com.zandequan.modules.oss.service.SysOssService;
import com.zandequan.common.utils.*;
import com.zandequan.modules.oss.cloud.CloudStorageConfig;
import com.zandequan.modules.oss.cloud.OSSFactory;
import com.zandequan.common.validator.ValidatorUtils;
import com.zandequan.common.validator.group.AliyunGroup;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 文件上传
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController extends AbstractController {
	@Autowired
	private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<SysOssEntity> sysOssList = sysOssService.queryList(query);
		int total = sysOssService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(sysOssList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}


    /**
     * 云存储配置信息
     */
    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


	/**
	 * 保存云存储配置信息
	 */
	@RequestMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == Constant.CloudService.QINIU.getValue()){
			//校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuGroup.class);
		}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
			//校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunGroup.class);
		}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
			//校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudGroup.class);
		}
		

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}
	

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		//上传文件
		String url = OSSFactory.build().upload(file.getBytes());

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);

		return R.ok().put("url", url);
	}


	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.deleteBatch(ids);

		return R.ok();
	}

	/**
	 * aliyun upload callback
	 */
	@RequestMapping("/aliyun/upload")
	public R get(@RequestParam("filename") String filename,@RequestParam("fileType") String fileType){
		String endpoint = "oss-cn-beijing.aliyuncs.com";
		String accessId = "LTAIMOoUR9oRJzBK";
		String accessKey = "w7zuLvHZUMSjXj2S1WfpFtT2kghnA2";
		String bucket = "oss-buluo-app";
		String dir = "buluo_app";
		String host = "http://" + bucket + "." + endpoint;
		Long userId = getUserId();
		OSSClient client = new OSSClient(endpoint, accessId, accessKey);
		JSONObject ja1 =null;
		try {
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");

			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);
			switch (fileType){
				case "video":{ break;}
				case "image":{ break;}
				case "audio":{ break;}
				default:{fileType ="other" ;break;}
			}
			filename = expireEndTime + getRandomChar(10)+filename;
			String url = dir+ File.separator+fileType+ File.separator+userId+File.separator+sd.format(expiration)+File.separator+filename;

			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("filePath", url);
			respMap.put("accessid", accessId);
			respMap.put("accessid", accessId);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			//respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			ja1 = JSONObject.fromObject(respMap);
			System.out.println(ja1.toString());
		} catch (Exception e) {
//            Assert.fail(e.getMessage());
		}
		return R.ok().put("data",ja1);
	}
	/**
	 * JAVA获得0-9,a-z,A-Z范围的随机数
	 * @param length 随机数长度
	 * @return String
	 */
	public static String getRandomChar(int length) {
		char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
				'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
		Random random = new Random();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < length; i++) {
			buffer.append(chr[random.nextInt(62)]);
		}
		return buffer.toString();
	}
}
